from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
from tortoise.exceptions import DoesNotExist
from app.models import User, UserRoleEnum
from app.auth import decode_access_token
from datetime import datetime

# 声明全局 Bearer 实例
oauth2_scheme = HTTPBearer()

# 主依赖：解析 token -> User
async def get_current_user(token=Depends(oauth2_scheme)) -> User:
    """
    通过 HTTPBearer 解析 token，返回已验证的用户对象
    """
    payload = decode_access_token(token.credentials)
    if payload is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )

    user_id = payload.get("sub")
    if user_id is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="令牌缺少用户标识",
            headers={"WWW-Authenticate": "Bearer"},
        )

    try:
        user = await User.get(id=int(user_id))
    except (DoesNotExist, ValueError):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在",
            headers={"WWW-Authenticate": "Bearer"},
        )

    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户已被禁用",
        )

    # 可选：更新最后登录时间
    user.last_login = datetime.now()
    await user.save()
    return user

# 3⃣ 后续权限依赖（保持原逻辑）
async def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
    return current_user

async def require_admin(current_user: User = Depends(get_current_active_user)) -> User:
    if current_user.role not in [UserRoleEnum.ADMIN, UserRoleEnum.SUPER_ADMIN]:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="需要管理员权限")
    return current_user

async def require_super_admin(current_user: User = Depends(get_current_active_user)) -> User:
    if current_user.role != UserRoleEnum.SUPER_ADMIN:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="需要超级管理员权限")
    return current_user